package com.study.spmongodb.book.wwj.char05;

import java.util.LinkedList;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/25 7:29
 */
public class EventQueue {

    private final int max;

    static class Event {

    }

    private final LinkedList<Event> eventQueue = new LinkedList<>();

    private final static int DEFAULT_MAX_EVENTS = 10;

    public EventQueue() {
        this(DEFAULT_MAX_EVENTS);
    }

    public EventQueue(int max) {
        this.max = max;
    }

    /**
     * 提价event到队尾，如果满足就阻塞
     *
     * @param event
     */
    public void offer(Event event) {
        synchronized (eventQueue) {
            if (eventQueue.size() >= max) {
                try {
                    console(" the queue is full.");
                    eventQueue.wait();
                } catch (InterruptedException e) {

                }
            }
            console(" the new event is submitted ");
            eventQueue.addLast(event);
            eventQueue.notifyAll();
        }
    }

    public Event take() {
        synchronized (eventQueue) {
            while (eventQueue.isEmpty()) {
                console(" the event is empty.");
                try {
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            final Event event = eventQueue.removeFirst();
            this.eventQueue.notifyAll();
            console(" the event " + event + " is handdled.");
            return event;
        }
    }


    private void console(String msg) {
        System.out.printf("%s:%s\n", Thread.currentThread().getName(), msg);
    }
}
